package com.example.NetworkSender.ui;

import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.example.NetworkSender.Engine;

import java.util.StringTokenizer;

public class SendListener implements View.OnClickListener {

    private final Engine engine;
    private final EditText input;
    private final EditText tbAddress;

    public SendListener(Engine engine, EditText input, EditText tbAddress) {
        this.engine = engine;
        this.input = input;
        this.tbAddress = tbAddress;
    }

    @Override
    public void onClick(View v) {
        try {
            checkEngine();
            int[] data = readFromScreen();
            String address = tbAddress.getText().toString();
            Log.e("bef send", "bef send");
            engine.send(data, address);
            input.setText("sent: " + input.getText());
        } catch (Exception ex) {
            Log.e("SendListener.OnClick", ex.getMessage());
        }
    }

    private void checkEngine() {
        if (engine == null) {
            throw new IllegalStateException("SendListener.OnClick: engine is null");
        }
        if (!engine.readyToSend()) {
            throw new IllegalStateException("SendListener.OnClick: engine is not ready");
        }
    }

    private int[] readFromScreen() {
        StringTokenizer tokenizer = new StringTokenizer(input.getText().toString());
        int size = tokenizer.countTokens();
        int[] bufferWrite = new int[size];
        for (int i = 0; i < size && tokenizer.hasMoreTokens(); i++) {
            bufferWrite[i] = Integer.parseInt(tokenizer.nextToken());
        }
        return bufferWrite;
    }
}
